package com.github.bridge.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.bridge.domain.SysConfig;
import com.github.bridge.service.WeightConfigService;
import com.github.bridge.util.Const;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import wiki.xsx.core.handler.HashHandler;
import wiki.xsx.core.util.RedisUtil;

@Slf4j
@Component
@RequiredArgsConstructor
public class SysConfigHandler {
    private final WeightConfigService weightConfigService;

    public SysConfig findBySystemId(String systemId) {
        HashHandler hashHandler = RedisUtil.getHashHandler();
        String configStr = hashHandler.get(Const.SYSTEM_CONFIG_KEY, systemId);
        if (StrUtil.isBlank(configStr)) {
            SysConfig sysConfig = weightConfigService.findBySystemId(systemId);
            if (ObjectUtil.isNull(sysConfig)) {
                throw new RuntimeException("未找到:" + systemId + "的系统配置");
            } else {
                hashHandler.put(Const.SYSTEM_CONFIG_KEY, systemId, JSONUtil.toJsonStr(sysConfig));
                return sysConfig;
            }
        } else {
            return JSONUtil.toBean(configStr, SysConfig.class);
        }
    }

    public String findSecretBySystemId(String systemId) {
        HashHandler hashHandler = RedisUtil.getHashHandler();
        String configStr = hashHandler.get(Const.SYSTEM_CONFIG_KEY, systemId);
        if (StrUtil.isBlank(configStr)) {
            SysConfig sysConfig = weightConfigService.findBySystemId(systemId);
            if (ObjectUtil.isNull(sysConfig)) {
                throw new RuntimeException("未找到:" + systemId + "的系统配置");
            } else {
                hashHandler.put(Const.SYSTEM_CONFIG_KEY, systemId, JSONUtil.toJsonStr(sysConfig));
                return sysConfig.getSecret();
            }
        } else {
            SysConfig sysConfig = JSONUtil.toBean(configStr, SysConfig.class);
            return sysConfig.getSecret();
        }
    }
}
